#include "StdAfx.h"
#include "LogFile.h"

using namespace std;

CLogFile::CLogFile( void )
{
}

CLogFile::~CLogFile(void)
{
}

bool CLogFile::Open( const tstring& strFile )
{
	if( m_iFile.is_open() )
	{
		m_iFile.clear();
		m_iFile.seekg(0, ios_base::beg);

		return true;
	}

	m_iFile.open( strFile.c_str() );
	return m_iFile.is_open();
}


bool CLogFile::PickPrice( PRICE_RECORD& rcdPrice )
{
	tstring strLine;
	if( !ReadLine( strLine ) )
	{
		return false;
	}

	if( !ParseLine( strLine, rcdPrice ) )
	{
		return false;
	}

	return true;
}

bool CLogFile::ReadLine( tstring& strLine )
{
	wchar_t szLine[1024];
	if( m_iFile.eof() )
	{
		return false;
	}

	if( !m_iFile.getline(szLine, sizeof(szLine)) )
	{
		return false;
	}

	strLine = szLine;

	return true;
}

bool CLogFile::ParseLine( const tstring& strLine, PRICE_RECORD& rcdPrice ) const
{
	const TCHAR DELIMITER = _T(',');

	// time
	tstring::size_type nComma1st = strLine.find( DELIMITER );
	if( tstring::npos == nComma1st )
	{
		return false;
	}

	tstring strTime = strLine.substr( 0, nComma1st );
	DelSpace( strTime );

	// count
	++nComma1st;
	tstring::size_type nComma2nd = strLine.find( DELIMITER, nComma1st );
	if( tstring::npos == nComma2nd )
	{
		return false;
	}
	
	tstring strCount = strLine.substr( nComma1st, nComma2nd-nComma1st );
	DelSpace( strCount );
	
	// price
	++nComma2nd;
	tstring::size_type nComma3rd = strLine.find( DELIMITER, nComma2nd );
	if( tstring::npos == nComma3rd )
	{
		return false;
	}
	
	tstring strPrice = strLine.substr( nComma2nd, nComma3rd - nComma2nd );
	DelSpace( strPrice );

	// flag
	tstring::size_type nCommaLast = strLine.rfind( DELIMITER );
	if( tstring::npos == nCommaLast )
	{
		return false;
	}

	++nCommaLast;
	tstring strFlag = strLine.substr( nCommaLast, strLine.length() - nCommaLast );
	DelSpace( strFlag );

	// 
	rcdPrice.strTime = strTime;
	rcdPrice.strCount = strCount;
	rcdPrice.strPrice = strPrice;
	rcdPrice.strFlag = strFlag;

	return true;
}	
